<?php

namespace app\api\controller;

use app\common\model\ArticleModel;
use app\common\model\CarBrandModel;
use app\common\model\CarLicenseMoreModel;
use app\common\model\CarModel;
use app\common\model\CarSeriesModel;
use app\common\model\MemberModel;
use app\common\model\SystemMsgModel;
use app\common\model\UserActionModel;
use app\common\model\UserCarMessageModel;
use app\common\model\UserCarModel;
use app\common\model\UserCollectModel;
use think\facade\Config;
use think\db;
use think\App;
use think\facade\Cache;
use think\Request;

class InfoController extends BaseController
{


    /**
     * 所有车辆
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function index(Request $request)
    {
        $where = $this->search($request);

        //排序
        $car_order = $request->order ?: 0;
        $more = $request->more; //其它条件

        $keyword = $request->keyword; //关键字


        //亮点配置
        $orWhere = [];
        if (!empty($more)) {
            $more = json_decode($more, true);
            if (!empty($more["labArr"])) {
                $arr = [];
                foreach ($more["labArr"] as $item) {
                    $arr[] = ['like', "%{$item}%"];
                }

                if (count($arr) > 0) {
                    if (count($arr) < 2) {
                        $orWhere[] = ['add_conf', 'like', $arr[0][1]];
                    } else {
                        $orWhere[] = ['add_conf', $arr, "or"];
                    }
                }
            }
        }


        //排序
        $orderArr = [
            0 => "refresh_time desc,create_time desc", //智能排序
            1 => "create_time desc,refresh_time desc", //最新上架
            2 => "price asc,refresh_time desc", //价格最低
            3 => "price desc,refresh_time desc", //价格最高
            4 => "card_time des,refresh_time desc", //车辆最新
            5 => "mileage asc,refresh_time desc", //历程最少
        ];

        $field = "id,vin,series_id,car_id,head_img,img_list,good_numb,collect_count,msg_count,mileage,price,card_time";
        $model = Db::name('user_car')
            ->field($field)
            ->where($where)
            ->where('status', UserCarModel::SHOW_STATUS)
            ->where('publish_time', '<=', time())
            ->where($orWhere);

        if (!empty($keyword)){
            $b="";
            $c="";
            $brandList=CarBrandModel::field("brand_id")->where('brand','like',"%{$keyword}%")->select();
            if(!empty($brandList)){
                $ids = array_column($brandList->toArray(), 'brand_id');
                $b = implode(',',$ids);//数组转换成字符串
            }

            $seriesList=CarSeriesModel::field("series_id")->where('series_name','like',"%{$keyword}%")->select();
            if(!empty($seriesList)){
                $ids = array_column($seriesList->toArray(), 'series_id');
                $c = implode(',',$ids);//数组转换成字符串
            }

            if(!empty($b) && !empty($c)) $model->where("brand_id in({$b}) or series_id in({$c})");
            else if(!empty($b)) $model->where("brand_id","in",$b);
            else if(!empty($c)) $model->where("series_id","in",$c);

            if(empty($b) && empty($c)){
                $model->where("id",-1);
            }
        }




        $list = $model->order($orderArr[$car_order])
            ->paginate(10);

        $newList = [];
        foreach ($list as $item) {
            $item["series"] = CarSeriesModel::field('series_name,thumb')->where('series_id', $item["series_id"])->find();
            $item["img_list"] = json_decode($item["img_list"], true);
            $item["car_name"]="";

            if(!empty($item['vin'])){
                $carVin=CarLicenseMoreModel::field("sale_name,brand_name,year")->where('vin','=',$item['vin'])->find();
                $item["car_name"]=$carVin['brand_name']." ".$carVin['year']."款 ".$carVin['sale_name'];
            }else{
                if($item['car_id']){
                    $car = CarModel::field('car_name,series_max,car_case')->where('car_id',$item['car_id'])->find();
                    if(!empty($car))
                    $item["car_name"] = $car->car_name;
                }
            }

            $item["collectCount"] = UserCollectModel::field("id")
                ->where('user_car_id', $item["id"])
                ->where("status", UserCollectModel::SHOW_STATUS)
                ->count();

            $item["msgCount"] = UserCarMessageModel::field("id")
                ->where('user_car_id', $item["id"])
                ->where("status", UserCarMessageModel::SHOW_STATUS)
                ->count();

            $newList[] = $item;
        }

        return backSuccess($newList);
    }

    public function index_back(Request $request)
    {
        $where = $this->search($request);

        //排序
        $car_order = $request->order ?: 0;
        $more = $request->more; //其它条件

        $keyword = $request->keyword; //关键字


        //亮点配置
        $orWhere = [];
        if (!empty($more)) {
            $more = json_decode($more, true);
            if (!empty($more["labArr"])) {
                $arr = [];
                foreach ($more["labArr"] as $item) {
                    $arr[] = ['like', "%{$item}%"];
                }

                if (count($arr) > 0) {
                    if (count($arr) < 2) {
                        $orWhere[] = ['u.add_conf', 'like', $arr[0][1]];
                    } else {
                        $orWhere[] = ['u.add_conf', $arr, "or"];
                    }
                }
            }
        }


        //排序
        $orderArr = [
            0 => "u.refresh_time desc,u.adopt_time desc", //智能排序
            1 => "u.create_time desc,u.refresh_time desc", //最新上架
            2 => "u.price asc,u.refresh_time desc", //价格最低
            3 => "u.price desc,u.refresh_time desc", //价格最高
            4 => "u.card_time desc,u.refresh_time desc", //车辆最新
            5 => "u.mileage asc,u.refresh_time desc", //历程最少
        ];

        $field = "u.*,car.car_id,car.series_thumb,car.car_name,car.brand,car.car_pl_l,car.car_bsxlx,car.car_hbbz,car.car_seat,car.car_rlxs";
        $model = Db::name('user_car')->alias("u")
            ->join("erc_car car", "car.car_id=u.car_id", "LEFT")
            ->field($field)
            ->where($where)
            ->where('u.status', UserCarModel::SHOW_STATUS)
            ->where('u.publish_time', '<=', time())
            ->where($orWhere);

        if (!empty($keyword)) $model->where("car.car_name like '{$keyword}' or car.brand like '{$keyword}'");

        $list = $model->order($orderArr[$car_order])
            ->paginate(10);

        $newList = [];
        foreach ($list as $item) {
            $item["series"] = CarSeriesModel::field('series_name,thumb')->where('series_id', $item["series_id"])->find();
            $item["img_list"] = json_decode($item["img_list"], true);

            if(!empty($item['vin'])){
                $carVin=CarLicenseMoreModel::field("sale_name")->where('vin','=',$item['vin'])->find();
                $item["car_name"]=$carVin['sale_name'];
            }

            $item["collectCount"] = UserCollectModel::field("id")
                ->where('user_car_id', $item["id"])
                ->where("status", UserCollectModel::SHOW_STATUS)
                ->count();

            $item["msgCount"] = UserCarMessageModel::field("id")
                ->where('user_car_id', $item["id"])
                ->where("status", UserCarMessageModel::SHOW_STATUS)
                ->count();

            $newList[] = $item;
        }

        return backSuccess($newList);
    }

    //汽车搜索
    public function searchCarKeyword(Request $request)
    {
        $keyword = $request->keyword;

        $field = "id,vin,series_id,car_id,img_list,head_img,good_numb,collect_count,msg_count,mileage,price,card_time";
        $model = Db::name('user_car')
            ->field($field)
            ->where('status', UserCarModel::SHOW_STATUS)
            ->where('publish_time', '<=', time());

        if (!empty($keyword)){
            $b="";
            $c="";
            $brandList=CarBrandModel::field("brand_id")->where('brand','like',"%{$keyword}%")->select();
            if(!empty($brandList)){
                $ids = array_column($brandList->toArray(), 'brand_id');
                $b = implode(',',$ids);//数组转换成字符串
            }

            $seriesList=CarSeriesModel::field("series_id")->where('series_name','like',"%{$keyword}%")->select();
            if(!empty($seriesList)){
                $ids = array_column($seriesList->toArray(), 'series_id');
                $c = implode(',',$ids);//数组转换成字符串
            }
            if(!empty($b) && !empty($c)) $model->where("brand_id in({$b}) or series_id in({$c})");
            else if(!empty($b)) $model->where("brand_id","in",$b);
            else if(!empty($c)) $model->where("series_id","in",$c);

            if(empty($b) && empty($c)){
                $model->where("id",-1);
            }
        }

        $list = $model->paginate(3);

        $newList = [];
        foreach ($list as $item) {
            $item["series"] = CarSeriesModel::field('series_name,thumb')->where('series_id', $item["series_id"])->find();
            $item["img_list"] = json_decode($item["img_list"], true);
            if(!empty($item["series"])){
                $item["series"]["series_thumb"] = $item["series"]['thumb'];
            }
            $item["car_name"]="";


            if(!empty($item['vin'])){
                $carVin=CarLicenseMoreModel::field("sale_name,brand_name,year")->where('vin','=',$item['vin'])->find();
                $item["car_name"]=$carVin['brand_name']." ".$carVin['year']."款 ".$carVin['sale_name'];
            }else{
                if($item['car_id']){
                    $car = CarModel::field('car_name,series_max,car_case')->where('car_id',$item['car_id'])->find();
                    if(!empty($car))
                    $item["car_name"] = $car->car_name;
                }
            }

            $item["collectCount"] = UserCollectModel::field("id")
                ->where('user_car_id', $item["id"])
                ->where("status", UserCollectModel::SHOW_STATUS)
                ->count();

            $item["msgCount"] = UserCarMessageModel::field("id")
                ->where('user_car_id', $item["id"])
                ->where("status", UserCarMessageModel::SHOW_STATUS)
                ->count();

            $newList[] = $item;
        }
        //搜索文章
        $list = ArticleModel::getList(0, 3, ['title' => $keyword]);

        $data = [
            'carList' => $newList,
            'article' => $list['list'],
        ];

        return backSuccess($data);
    }

    /**
     * 搜索
     * @param $request
     * @return array
     */
    public function search(Request $request)
    {
        $where = [];

        $car_level = $request->car_level; //车辆类型
        $brand_id = $request->brand_id; //车辆品牌
        $series_id = $request->series_id; //车辆款型
        $minMoney = $request->minMoney; //最小金额
        $maxMoney = $request->maxMoney; //最大金额

        $more = $request->more; //其它条件

        //车辆类型
//        if (!empty($car_level)) {
//            $where[] = ["car.car_jg", 'like', "%{$car_level}%"];
//        }

        //车辆品牌
        if (!empty($brand_id)) {
            $where[] = ["brand_id", '=', $brand_id];
        }

        //车辆款型
        if (!empty($series_id)) {
            $where[] = ["series_id", '=', $series_id];
        }

        //价格
        if (!empty($minMoney) && empty($maxMoney)) {
            $where[] = ["price", ">", $minMoney];
        }

        if (empty($minMoney) && !empty($maxMoney)) {
            $where[] = ["price", "between", [0, $maxMoney]];
        }

        if (!empty($minMoney) && !empty($maxMoney)) {
            $where[] = ["price", "between", [$minMoney, $maxMoney]];
        }

        //其它条件
        if (!empty($more)) {
            $more = json_decode($more, true);

            //车辆类型
            if (!empty($more['typeVal'])) {
                $where[] = ["car_level", '=', $more['typeVal']];
            }

            //车牌所在地
            if (!empty($more['card_come'])) {

                if ($more['card_come'] == 1) {
                    $where[] = ["card_come", '=', "渝"];
                } else {
                    $where[] = ["card_come", '<>', "渝"];
                }
            }

            //车龄
            if (!empty($more['year_old'])) {
                $time = date('Y-m-d', strtotime("-{$more['year_old']} year"));
                $where[] = ["card_time", '>=', $time];
            }

            //里程
            if (!empty($more['go_long'])) {
                $where[] = ["mileage", '<=', $more['go_long']];
            }

            //颜色
            if (!empty($more['color'])) {
                $where[] = ["car_color", '=', $more['color']];
            }

//            if (!empty($more['row_amount'])) {
//                $where[] = ['car.car_pl_l', '=', $more["row_amount"]];
//            }

            //排放标准
//            if (!empty($more['car_dis'])) {
//                $arr = [
//                    2 => "国II",
//                    3 => "国III,国IV,国V,国VI",
//                    4 => "国IV,国V,国VI",
//                    5 => "国V,国VI",
//                    6 => "国VI,国VII,国VIII,国IX",
//                ];
//
//                $where[] = ['car.car_hbbz', 'in', $arr[$more["car_dis"]]];
//            }

            //座位数
            /*if (!empty($more['seat_numb'])) {
                $where[] = ['car.car_seat', '=', $more["seat_numb"]];
            }

            //油
            if (!empty($more['oil_type'])) {
                $where[] = ['car.car_rlxs', '=', $more["oil_type"]];
            }*/

            //变速箱
            /*if (!empty($more['car_case'])) {

                if ($more['car_case'] == 1) {
                    $where[] = ['car.car_case', 'like', '%手%'];
                } else {
                    $where[] = ["car.car_case", 'like', ['%自%', '%AMT%', '%无%', '%双%'], 'OR'];
                }


            }*/

            //TODO 国别

        }


        return $where;
    }

    public function search_back(Request $request)
    {
        $where = [];

        $car_level = $request->car_level; //车辆类型
        $brand_id = $request->brand_id; //车辆品牌
        $series_id = $request->series_id; //车辆款型
        $minMoney = $request->minMoney; //最小金额
        $maxMoney = $request->maxMoney; //最大金额

        $more = $request->more; //其它条件

        //车辆类型
        if (!empty($car_level)) {
            $where[] = ["car.car_jg", 'like', "%{$car_level}%"];
        }

        //车辆品牌
        if (!empty($brand_id)) {
            $where[] = ["u.brand_id", '=', $brand_id];
        }

        //车辆款型
        if (!empty($series_id)) {
            $where[] = ["u.series_id", '=', $series_id];
        }

        //价格
        if (!empty($minMoney) && empty($maxMoney)) {
            $where[] = ["u.price", ">", $minMoney];
        }

        if (empty($minMoney) && !empty($maxMoney)) {
            $where[] = ["u.price", "between", [0, $maxMoney]];
        }

        if (!empty($minMoney) && !empty($maxMoney)) {
            $where[] = ["u.price", "between", [$minMoney, $maxMoney]];
        }

        //其它条件
        if (!empty($more)) {
            $more = json_decode($more, true);

            //车辆类型
            if (!empty($more['typeVal'])) {
                $where[] = ["u.car_level", '=', $more['typeVal']];
            }

            //车牌所在地
            if (!empty($more['card_come'])) {

                if ($more['card_come'] == 1) {
                    $where[] = ["u.card_come", '=', "渝"];
                } else {
                    $where[] = ["u.card_come", '<>', "渝"];
                }
            }

            //车龄
            if (!empty($more['year_old'])) {
                $time = date('Y-m-d', strtotime("-{$more['year_old']} year"));
                $where[] = ["u.card_time", '>=', $time];
            }

            //里程
            if (!empty($more['go_long'])) {
                $where[] = ["u.mileage", '<=', $more['go_long']];
            }

            //颜色
            if (!empty($more['color'])) {
                $where[] = ["u.car_color", '=', $more['color']];
            }

            if (!empty($more['row_amount'])) {
                $where[] = ['car.car_pl_l', '=', $more["row_amount"]];
            }

            //排放标准
            if (!empty($more['car_dis'])) {
                $arr = [
                    2 => "国II",
                    3 => "国III,国IV,国V,国VI",
                    4 => "国IV,国V,国VI",
                    5 => "国V,国VI",
                    6 => "国VI,国VII,国VIII,国IX",
                ];

                $where[] = ['car.car_hbbz', 'in', $arr[$more["car_dis"]]];
            }

            //座位数
            if (!empty($more['seat_numb'])) {
                $where[] = ['car.car_seat', '=', $more["seat_numb"]];
            }

            //油
            if (!empty($more['oil_type'])) {
                $where[] = ['car.car_rlxs', '=', $more["oil_type"]];
            }

            //变速箱
            if (!empty($more['car_case'])) {

                if ($more['car_case'] == 1) {
                    $where[] = ['car.car_case', 'like', '%手%'];
                } else {
                    $where[] = ["car.car_case", 'like', ['%自%', '%AMT%', '%无%', '%双%'], 'OR'];
                }


            }

            //TODO 国别

        }


        return $where;
    }

    /**
     * 车辆详情
     * @param int id 车辆的car_id
     * @param Request $request
     * @return \think\response\Json
     */
    public function details(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }
        $id = $request->id;
        $ip = $request->ip;

        $car = new UserCarModel();
        $info = $car->details($id, $ip);

        if (empty($info)) {
            return backError("未找到车辆！", 404);
        }

        //浏览记录
        if ($request->user) {
            if (empty(Cache::get("user_history_" . $request->user['uid']))) {
                $data[] = $info;
                Cache::set("user_history_" . $request->user['uid'], $data, 8640 * 7);
            } else {
                $data = Cache::get("user_history_" . $request->user['uid']);

                $count = count($data);
                $len = 15; //缓存15条数据
                $isHave = false;
                $arr = [];
                foreach ($data as $key => $item) {
                    if ($count >= $len && $key == 0) {
                        continue;
                    }

                    if ($item['id'] == $info["id"]) {
                        $isHave = true;
                        continue;
                    }

                    $arr[] = $item;
                }

                if (!$isHave) {
                    $arr[] = $info;
                    Cache::set("user_history_" . $request->user['uid'], $arr, 8640 * 7);
                }

            }

            $collectCount = UserCollectModel::where('user_id', $request->user['uid'])
                ->where('user_car_id', $id)
                ->count();

            $info['collectStatus'] = $collectCount;

            $info["goodStatus"] = UserActionModel::checkGood($request->user['uid'], $id, 0);

            $info['msgCount'] = UserCarMessageModel::where("user_car_id", $id)
                ->where("status", UserCarMessageModel::SHOW_STATUS)
                ->count();

        }


        return backSuccess($info);
    }

    /**
     * 用户浏览记录
     * @param Request $request
     * @return mixed
     */
    public function getUserHistory(Request $request)
    {
        $list = Cache::get("user_history_" . $request->user['uid']);

        return backSuccess($list);
    }

    /**
     * 收藏
     * @param Request $request
     * @return \think\response\Json
     */
    public function userCollect(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $car_id = $request->car_id;
        $user_id = $request->user['uid'];

        $M = new UserCollectModel();

        $info = UserCollectModel::where('user_car_id', $id)
            ->where('car_id', $car_id)
            ->where('user_id', $user_id)
            ->find();

        if ($info) {
            $res = $info->delete();

            $status['status'] = $res;
            UserActionModel::del($user_id, $id, 0, 'collect');
        } else {
            $data = [
                'user_car_id' => $id,
                'car_id' => $car_id,
                'user_id' => $user_id
            ];
            $status = $M->adds($data);

            UserActionModel::adds($user_id, $id, 0, 'collect');

        }


        if ($status['status']) {
            return backSuccess();
        } else {
            return backError($status['msg']);
        }
    }

    /**
     * 详情指定汽车用户留言列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function message(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $msg = new UserCarMessageModel();

        $list = $msg->getUserList($id);

        return backSuccess($list);
    }

    /**
     * 用户留言点赞
     * @param Request $request
     * @return \think\response\Json
     */
    public function goodMsg(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $ip = $request->ip();
        $user_id = $request->user['uid'];

        $t = Cache::get($ip . "_" . $id);
        if (!empty($t) && time() - $t <= (60 * 60 * 24)) {
            return backError('请勿频繁操作！');
        } else {
            Cache::set($ip . "_" . $id, time(), 60 * 60 * 24);
        }

        $info = UserCarMessageModel::get($id);

        if (empty($info) || empty($user_id)) {
            return backError('参数错误！');
        }

        $check = UserActionModel::checkGood($user_id, 0, 0, $id);

        if ($check) {
            $info->good_numb = $info->good_numb - 1;
            UserActionModel::del($user_id, 0, 0, 'good', $id);
        } else {
            $info->good_numb = $info->good_numb + 1;
            UserActionModel::adds($user_id, 0, 0, 'good', $id);
        }
        $status = $info->save();

        if ($status) {
            return backSuccess($info->good_numb);
        } else {
            return backError('参数错误！');
        }
    }

    /**
     * 汽车详情点赞
     * @param Request $request
     * @return \think\response\Json
     */
    public function carGood(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $user_id = $request->user['uid'];

        $info = UserCarModel::get($id);

        if (empty($info) || empty($user_id)) {
            return backError('参数错误！');
        }

        $check = UserActionModel::checkGood($user_id, $id, 0);

        if ($check) {
            $info->good_numb = $info->good_numb - 1;
            UserActionModel::del($user_id, $id, 0, 'good');
        } else {
            $info->good_numb = $info->good_numb + 1;
            UserActionModel::adds($user_id, $id, 0, 'good');
        }

        $info->good_numb = $info->good_numb + 1;
        $status = $info->save();

        if ($status) {
            return backSuccess($info->good_numb);
        } else {
            return backError('参数错误！');
        }
    }

    /**
     * 汽车留言
     * @param Request $request
     * @return \think\response\Json
     */
    public function carMsg(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        if (empty($request->msg)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $pid = $request->pid ? $request->pid : 0;
        $msg = $request->msg;
        $user_id = $request->user['uid'];

        $M = new UserCarMessageModel();

        $autoTime = getSystem("auto_push_time");
        $publish_time = time() + (60 * $autoTime);

        $data = [
            'user_car_id' => $id,
            'pid' => $pid,
            'user_id' => $user_id,
            'content' => $msg,
            'status' => 1,
            'publish_time' => $publish_time,
            'create_time' => time(),
        ];
        $status = $M->adds($data);

        if ($status['status']) {

            UserActionModel::adds($user_id, $id, 0, 'msg', $status['id']);

            //佣金
            if ($pid > 0) {
                $info = UserCarMessageModel::find($pid);
                if (!empty($info) && $user_id != $info["user_id"]) {
                    MemberModel::pushGold($user_id, 1,$status['id']);
                }
            } else {
                MemberModel::pushGold($user_id, 1,$status['id']);
            }

            return backSuccess();
        } else {
            return backError('留言失败，请稍后再试！');
        }
    }

    /**
     * 获取汽车品牌
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function carBrand(Request $request)
    {
        $keyword = $request->keyword;
        $where = [];
        if (!empty($keyword)) {
            $where[] = ['brand', 'like', "%{$keyword}%"];
        }
        $list = CarBrandModel::getList($where);
        $hot = CarBrandModel::getList(['shot' => 1]);

        $data = [
            'list' => $list,
            'hot' => $hot
        ];

        return backSuccess($data);
    }

    /**
     * 获取汽车品牌
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function carSeries(Request $request)
    {
        $brand_id = $request->id;
        $type = $request->type;

        if (empty($type)) {
            $list = CarSeriesModel::cache()
                ->field("series_name,series_id,thumb,brand_id")
                ->where('brand_id', $brand_id)
                ->where('status', CarSeriesModel::SHOW_STATUS)
                ->select();
        } else {
            $field = "car.series_name,car.series_id,car.thumb,car.brand_id";
            $list = Db::name('Car')->alias("c")
                ->join("erc_car_series car", "car.series_id=c.series_id", "LEFT")
                ->cache()
                ->field($field)
                ->distinct("car.series_id")
                ->where('c.brand_id', $brand_id)
                ->where('car.status', CarSeriesModel::SHOW_STATUS)
                ->select();
        }

        return backSuccess($list);
    }

    /**
     * 获取汽车
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getCar(Request $request)
    {
        $series_id = $request->id;
        $type = $request->type ? $request->type : 0;

        $model = CarModel::cache()
            ->field("car_name,car_id,series_thumb,brand_id,car_case,series_max")
            ->where('series_id', $series_id)
            ->where('status', CarSeriesModel::SHOW_STATUS);

        if ($type == 1) {
            $model->where('car_case', 'like', ['%自%', '%AMT%', '%无%', '%双%'], 'OR');
        } else if ($type == 2) {
            $model->where('car_case', 'like', '%手%');
        }

        $list = $model->select();

        return backSuccess($list);
    }

    /**
     * PK数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getPkData(Request $request)
    {
        $ids = $request->id;

        $field = 'id,car_id,price,series_id,img_list,car_level,car_color,card_time,mileage,card_come,transfer_times,pledge,nature,car_case';

        $list = UserCarModel::where("id", "in", $ids)
            ->field($field)
            ->where('status', UserCarModel::SHOW_STATUS)
            ->select();

        $carField = "id,car_id,status,brand_logo,brand_id,series_id,series_name,brand_first,series_factory_id,update_time,car_nsys,car_wgys,car_xbz";
        foreach ($list as $item) {
            $car = CarModel::cache()
                ->field($carField, true)
                ->where('car_id', '=', $item->car_id)
                ->find();

            $item->car = $car;
            $item->img_list = json_decode($item->img_list, true);
            $item->series = CarSeriesModel::field('series_name,thumb')->where('series_id', $item->series_id)->find();
        }

        $data = [
            'list' => $list,
            'menu' => $title = Config::get('tableName.car')
        ];

        return backSuccess($data);
    }

    /**
     * PK数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getPkMini(Request $request)
    {
        $ids = $request->id;

        $field = 'id,vin';

        $car = UserCarModel::where("id", $ids)
            ->field($field)
            ->where('status', UserCarModel::SHOW_STATUS)
            ->find();

        $info=CarLicenseMoreModel::where('vin',$car['vin'])->find();

        $data = [
            'info' => $info->toArray(),
            'menu' => $title = Config::get('tableName.car_mini')
        ];

        return backSuccess($data);
    }

    /**
     * 消息未读数量
     * @param Request $request
     * @return \think\response\Json
     */
    public function msgCount(Request $request)
    {
        $user_id = $request->user["uid"];

        $sysCount = SystemMsgModel::where('send_user_id', 'in', [$user_id, '0'])
            ->where('read_status', 0)
            ->count();

        $uc = UserCarModel::field("id")
            ->where('status', UserCarModel::SHOW_STATUS)
            ->where("user_id", $user_id)
            ->select();

        $carMsgCount = 0;
        foreach ($uc as $vo) {
            $carMsgCount += UserActionModel::where('link_id', $vo['id'])
                ->where('type', 0)
                ->where('status', 0)
                ->count();
        }

        $data = [
            'sysCount' => $sysCount,
            'carMsgCount' => $carMsgCount,
            'count' => $sysCount + $carMsgCount,
        ];


        return backSuccess($data);
    }
}
